//
//  BasicDataManager.swift
//  GhostWorld
//
//  Created by Kam on 2018/4/26.
//  Copyright © 2018 LKGood. All rights reserved.
//

/*
 This manager is for downloading pre-needed data of app.
 */

import Foundation

class BasicDataManager {
  // MARK: - Singleton
  static let shared = BasicDataManager()
  private init() { }
  
  // MARK: - Public methods
  
  func processBasicOnlineData() {
    // load groups
    API.shared.requestAPI(APIURLStrings.allGroups, method: .get, successCallback: { json in
      if let groupsJSON = json["groups"].arrayObject as? [[String : Any]] {
        
        // sync groups to CoreData
        EntityManager.sync (
          type: Group.self,
          rawObject: groupsJSON,
          operations: [.update, .insert, .delete],
          completion: { error, groups in
            if error == nil {
              groups!.forEach { print($0) }
              print("\(groups!.count) groups in CoreData")
            } else {
              print("No groups in CoreData")
            }
        })
      }
    }) { (message, code) in
      loggingPrint("--- Groups data error! ---")
    }
    
    // load IAP productIDs
//    DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
//      API.shared.requestAPI(APIURLStrings.allIAPs, method: .get, successCallback: { json in
//        if let iapsJSON = json["iaps"].arrayObject as? [[String : Any]] {
//
//          // sync groups to CoreData
//          EntityManager.sync (
//            type: IAPProduct.self,
//            rawObject: iapsJSON,
//            operations: [.update, .insert, .delete],
//            completion: { error, iaps in
//              if error == nil {
//                iaps!.forEach { print($0.product ?? "--") }
//                print("\(iaps!.count) iaps in CoreData")
//              } else {
//                print("No iaps in CoreData")
//              }
//          })
//        }
//      }) { (message, code) in
//        loggingPrint("--- IAPs data error! ---")
//      }
//    }
  }
}
